package com.atguigu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseApp;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2023/3/11 10:18
 */
@Slf4j
public class DwdBaseLog extends BaseApp {
    private final static String START = "start";
    private final static String ERR = "err";
    private final static String ACTION = "action";
    private final static String PAGE = "page";
    private final static String DISPLAY = "display";
    
    public static void main(String[] args) {
        new DwdBaseLog().init(
            3001,
            2,
            "DwdBaseLog",
            Constant.TOPIC_ODS_LOG
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        
        // 1. 对数据进行清洗
        SingleOutputStreamOperator<String> etledStream = etl(stream);
        
        // 2. 纠正新老客户标记
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        // 3. 分流
        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);
        
        // 4. 写出到 kafka 中
        writeToKafka(streams);
        
    }
    
    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
       
    }
    
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        
        //        new OutputTag<List<String>>("a", TypeInformation.of(new TypeHint<List<String>>(){});
        //        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display", TypeInformation.of(JSONObject.class));
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action") {};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err") {};
    
       
        /*
        启动 : 主流
        
        页面  曝光 活动 错误: 4个侧输出流
         */
        SingleOutputStreamOperator<JSONObject> startStream = stream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");
    
                    // 启动日志
                    JSONObject start = obj.getJSONObject("start");
                    if (start != null) {
                        out.collect(obj);
                        
                    }
                    // 曝光
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            // 把 common 中的所有字段, 写入到 display 中
                            // display: {1: 10}
                            // common: {a: aa}
                            // 操作完: {1: 10, a: aa}
                            display.putAll(common);
                            display.putAll(page);
                            display.put("ts", ts);
                            ctx.output(displayTag, display);
                        }
                        // displays 字段从 obj 中删除, 将来的 page 页面就没有冗余信息
                        obj.remove("displays");
                    }
                    // 活动
                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            // 把 common 中的所有字段, 写入到 display 中
                            // display: {1: 10}
                            // common: {a: aa}
                            // 操作完: {1: 10, a: aa}
                            action.putAll(common);
                            action.putAll(page);
                            ctx.output(actionTag, action);
                        }
                        // actions 字段从 obj 中删除, 将来的 page 页面就没有冗余信息
                        obj.remove("actions");
                    }
                    
                    // 错误
                    JSONObject err = obj.getJSONObject("err");
                    if (err != null) {
                        ctx.output(errTag, obj);
    
                        obj.remove("err");
                    }
                    
                    // page
                    if (page != null) {
                        ctx.output(pageTag, obj);
                    }
                }
            });
    
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        DataStream<JSONObject> actionStream = startStream.getSideOutput(actionTag);
        DataStream<JSONObject> errStream = startStream.getSideOutput(errTag);
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        // 数组 list set 元组: 不方便的地方, 将来流的位置索引要对应正确
        // map 集合: 根据 key取
        Map<String, DataStream<JSONObject>> steams = new HashMap<>();
        steams.put(START, startStream);
        steams.put(ERR, errStream);
        steams.put(DISPLAY, displayStream);
        steams.put(PAGE, pageStream);
        steams.put(ACTION, actionStream);
        
        return steams;
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, JSONObject>() {
                
                private ValueState<String> firstVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitDateState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                }
                
                @Override
                public JSONObject map(JSONObject obj) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    
                    String isNew = common.getString("is_new");
                    
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    
                    String firstVisitDate = firstVisitDateState.value();
                    
                    if ("1".equals(isNew)) {
                        if (firstVisitDate == null) {  // 首次访问
                            firstVisitDateState.update(today); //把今天写入到状态中
                        } else {
                            if (!today.equals(firstVisitDate)) {
                                common.put("is_new", "0");
                            }
                        }
                    } else {
                        // 即使是老用户, 也需要修改下状态
                        // 表示今天肯定不是第一天, 如果状态又没有值.这时应该把状态设置一个今天之前的日期
                        if (firstVisitDate == null) {
                            firstVisitDateState.update(AtguiguUtil.tsToDate(ts - 24 * 60 * 60 * 1000));
                        }
                    }
                    
                    return obj;
                }
            });
    }
    
    private SingleOutputStreamOperator<String> etl(DataStreamSource<String> stream) {
        return stream
            .filter(new FilterFunction<String>() {
                @Override
                public boolean filter(String value) throws Exception {
                    try {
                        JSON.parseObject(value);
                        return true;
                    } catch (Exception e) {
                        log.warn("json 数据格式不正确: " + value);
                        return false;
                    }
                    
                }
            });
    }
}
/*
流量域事务事实表
    日志数据
    
    主要目的: 把 5 种日志分别写入到不同的 dwd 层 topic 中
    
 涉及到的技术:
    分流
        1 个流变成 5 个流
            测输出流
            
    写出到 kafka
        自定义序列化器
     
 ------
 新老客户标记纠正
 
 错误: 把老用户误识别新用户
 
   保存这个用户(mid) 首次访问日期, 每来一条数据判断今天与首次访问日期是否一致
   
   状态: 保存每个 mid 首次访问日期  监控状态中的: value
   
   is_new == 1
        状态 == null
            不需要修正
            把今天放入到状态中
        状态 != null
            今天和状态中的日期是否一致
                一致: 不用修正, 什么都不用做
                不一致: is_new=0
   

 */